package org.iartisan.thought.server.service.support;

import org.iartisan.runtime.env.EnvContextConfig;
import org.iartisan.runtime.utils.UUIDUtil;
import org.iartisan.thought.server.dbm.mapper.SystemTokenMapper;
import org.iartisan.thought.server.dbm.model.SystemTokenDO;
import org.iartisan.thought.server.service.constants.TokenBusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * token 服务
 *
 * @author King
 * @since 2018/4/3
 */
@Service
public class TokenSupportService {

    @Autowired
    private SystemTokenMapper systemTokenMapper;

    public String createEmailActiveToken(String userId) {
        String token = UUIDUtil.timeBaseId(32);
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + Integer.parseInt(EnvContextConfig.get("token.expire", "30")) * 3600 * 1000);
        //判断是否生成过token
        SystemTokenDO tokenQuery = new SystemTokenDO();
        tokenQuery.setUserId(userId);
        tokenQuery.setBusinessType(TokenBusinessType.email.name());
        SystemTokenDO tokenResult = systemTokenMapper.selectOne(tokenQuery);
        if (tokenResult == null) {
            //生成一个token
            tokenResult = new SystemTokenDO();
            tokenResult.setUserId(userId);
            tokenResult.setToken(token);
            tokenResult.setUpdateTime(now);
            tokenResult.setExpireTime(expireTime);
            systemTokenMapper.insert(tokenResult);
        } else {
            tokenResult.setToken(token);
            tokenResult.setUpdateTime(now);
            tokenResult.setExpireTime(expireTime);
            //更新token
            systemTokenMapper.updateById(tokenResult);
        }
        return token;
    }

    public SystemTokenDO getByToken(String token) {
        SystemTokenDO tokenQuery = new SystemTokenDO();
        tokenQuery.setToken(token);
        return systemTokenMapper.selectOne(tokenQuery);
    }

    public boolean checkToken(String token) {
        SystemTokenDO dbResult = getByToken(token);
        if (null != dbResult) {
            return true;
        }
        return false;
    }

    public void deleteToken(String token) {
        systemTokenMapper.deleteById(getByToken(token).getId());
    }

    public void refreshToken(String token) {
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + Integer.parseInt(EnvContextConfig.get("token.expire", "30")) * 3600 * 1000);
        SystemTokenDO dbResult = getByToken(token);
        if (null != dbResult) {
            //如果当前token没有失效
            if (dbResult.getExpireTime().getTime() > System.currentTimeMillis()) {
                dbResult.setExpireTime(expireTime);
                systemTokenMapper.updateById(dbResult);
            }
        }
    }
}
